/**
 * Cross-platform path detection utilities
 * Handles different operating system standards for configuration and log paths
 */

const os = require('os');
const path = require('path');

/**
 * Get configuration directory path for the current platform
 * @returns {string} Absolute path to configuration directory
 */
function getConfigDir() {
  const platform = os.platform();
  const homeDir = os.homedir() || '';

  switch (platform) {
    case 'win32':
      // Windows: %LOCALAPPDATA%\vision-analyzer\Config\
      const localAppData = process.env.LOCALAPPDATA || path.join(homeDir, 'AppData', 'Local');
      return path.join(localAppData, 'vision-analyzer', 'Config');
    case 'darwin':
      // macOS: ~/Library/Preferences/vision-analyzer/
      return path.join(homeDir, 'Library', 'Preferences', 'vision-analyzer');
    default: // linux and others
      // Linux: ~/.config/vision-analyzer/
      return path.join(homeDir, '.config', 'vision-analyzer');
  }
}

/**
 * Get configuration file path
 * @param {string} filename - Configuration file name (default: 'settings.json')
 * @returns {string} Absolute path to configuration file
 */
function getConfigPath(filename = 'settings.json') {
  return path.join(getConfigDir(), filename);
}

/**
 * Get log directory path for the current platform
 * @returns {string} Absolute path to log directory
 */
function getLogDir() {
  const platform = os.platform();
  const homeDir = os.homedir();

  switch (platform) {
    case 'win32':
      // Windows: %LOCALAPPDATA%\vision-analyzer\logs\
      return path.join(process.env.LOCALAPPDATA || path.join(homeDir, 'AppData', 'Local'), 'vision-analyzer', 'logs');
    case 'darwin':
      // macOS: ~/Library/Logs/vision-analyzer/
      return path.join(homeDir, 'Library', 'Logs', 'vision-analyzer');
    default: // linux and others
      // Linux: ~/.local/state/vision-analyzer/logs/
      return path.join(homeDir, '.local', 'state', 'vision-analyzer', 'logs');
  }
}

/**
 * Get log file path
 * @param {string} filename - Log file name (default: 'vision-analyzer.log')
 * @returns {string} Absolute path to log file
 */
function getLogPath(filename = 'vision-analyzer.log') {
  return path.join(getLogDir(), filename);
}

/**
 * Get alternative configuration directory (user-level fallback)
 * @returns {string} Absolute path to alternative configuration directory
 */
function getAlternativeConfigDir() {
  const homeDir = os.homedir();
  return path.join(homeDir, '.vision-analyzer');
}

/**
 * Get alternative configuration file path
 * @param {string} filename - Configuration file name
 * @returns {string} Absolute path to alternative configuration file
 */
function getAlternativeConfigPath(filename = 'settings.json') {
  return path.join(getAlternativeConfigDir(), filename);
}

/**
 * Check if a directory exists and is writable
 * @param {string} dirPath - Directory path to check
 * @returns {boolean} True if directory exists and is writable
 */
function isDirectoryWritable(dirPath) {
  try {
    const fs = require('fs');
    fs.accessSync(dirPath, fs.constants.W_OK);
    return true;
  } catch (error) {
    return false;
  }
}

/**
 * Ensure directory exists and is writable
 * @param {string} dirPath - Directory path to ensure
 * @returns {boolean} True if directory is ready for use
 */
function ensureDirectory(dirPath) {
  const fs = require('fs');

  try {
    if (!fs.existsSync(dirPath)) {
      fs.mkdirSync(dirPath, { recursive: true });
    }
    return true;
  } catch (error) {
    // Silently handle errors in test environment
    if (process.env.NODE_ENV !== 'test') {
      console.error(`Failed to create directory ${dirPath}:`, error);
    }
    return false;
  }
}

/**
 * Create directory recursively if it doesn't exist
 * @param {string} dirPath - Directory path to create
 * @returns {boolean} True if directory exists or was created successfully
 */
function createDirectory(dirPath) {
  const fs = require('fs');

  try {
    if (!fs.existsSync(dirPath)) {
      fs.mkdirSync(dirPath, { recursive: true });
    }
    return true;
  } catch (error) {
    // Silently handle errors in test environment
    if (process.env.NODE_ENV !== 'test') {
      console.error(`Failed to create directory ${dirPath}:`, error);
    }
    return false;
  }
}

/**
 * Get platform information object
 * @returns {Object} Platform information
 */
function getPlatformInfo() {
  return {
    platform: os.platform(),
    arch: os.arch(),
    release: os.release(),
    type: os.type(),
    homedir: os.homedir(),
    configDir: getConfigDir(),
    logDir: getLogDir()
  };
}

module.exports = {
  getConfigDir,
  getConfigPath,
  getLogDir,
  getLogPath,
  getAlternativeConfigDir,
  getAlternativeConfigPath,
  isDirectoryWritable,
  ensureDirectory,
  createDirectory,
  getPlatformInfo
};